package master

import (
	"context"
	"fmt"
	"study-crontab/crontab/common"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

type WorkerMgr struct {
	client *clientv3.Client
	kv     clientv3.KV
	lease  clientv3.Lease
}

var G_workerMgr *WorkerMgr

// NewWorkerMgr 初始化管理器
func NewWorkerMgr() error {
	config := clientv3.Config{
		Endpoints:   G_config.EtcdEndpoints,
		DialTimeout: time.Duration(G_config.EtcdDialTimeout) * time.Millisecond,
	}

	//建立连接
	client, err := clientv3.New(config)
	if err != nil {
		fmt.Println("etcd连接失败")
		return err
	}

	kv := clientv3.NewKV(client)
	lease := clientv3.NewLease(client)

	G_workerMgr = &WorkerMgr{
		client: client,
		kv:     kv,
		lease:  lease,
	}

	return nil
}

//获取在线worker列表
func (w *WorkerMgr) ListWorkers() (workerArr []string, err error) {
	jobKey := common.REGISTER_WORKERS_DIR

	//etcd中目录下所有任务
	getResp, err := w.kv.Get(context.TODO(), jobKey, clientv3.WithPrefix())
	if err != nil {
		return nil, err
	}
	workerArr = make([]string, 0)
	//遍历所有任务
	for _, v := range getResp.Kvs {
		ip := common.ExtractWorkerIp(string(v.Key))
		workerArr = append(workerArr, ip)
	}

	return
}
